package dx.util;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.jetbrains.annotations.Nullable;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;

/**
 * JSON操作类
 * create by duanx 2021/7/4
 *@description： JSON操作类
 *@classname: JsonUtil
 *@author: duanx
 *@date: 2021/7/4 0:31
 **/


public class JsonUtil extends BaseUtil {


    /**
     * 读取json文件
     * @param fileName 文件名 文件路径在resources下的
     * @return json字符串
     */
    @Nullable
    public static String readJsonFile(String fileName) {
        logger.debug("开始读取"+fileName+"文件");
        String jsonStr;
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), StandardCharsets.UTF_8);
            int ch;
            StringBuilder sb = new StringBuilder();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            logger.debug("读取"+fileName+"文件成功！");
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            logger.debug("读取文件"+fileName+"失败！"+e.toString());
            return null;
        }
    }

    public static JSONObject objToJSONObject(Object object) {
        if(null == object){
            return null;
        }
        return (JSONObject) JSON.toJSON(object);
    }

    public static void main(String[] args) {

        String filePath = "D:\\Java\\item\\sc\\tryod\\oho\\src\\main\\resources\\b.json";
        String json = JsonUtil.readJsonFile(filePath);

        Map map = JSONUtil.toBean(json, Map.class);
        cn.hutool.json.JSONObject resultJsonObj = JSONUtil.parseObj(map.get("result"));
        JSONArray array = (JSONArray) resultJsonObj.get("item_list");
        for (Object o:array){
            JSONObject object = objToJSONObject(o);
            String key = object.getString("key");
            System.out.println(key+":"+object.getString("value"));

        }

    }

}
